package com.nari.ysphd.view;

import java.util.ArrayList;
import java.util.List;

import com.intel.webrtc.base.ActionCallback;
import com.intel.webrtc.base.RemoteScreenStream;
import com.intel.webrtc.base.RemoteStream;
import com.intel.webrtc.base.WoogeenException;
import com.intel.webrtc.conference.ConferenceClient;
import com.intel.webrtc.conference.RemoteMixedStream;
import com.jeremyfeinstein.conference.YCHSConferenceClient;
import com.nari.ysphd.R;
import com.jeremyfeinstein.event.DoubleClickListener;
import com.jeremyfeinstein.gson.MeetingUser;
import com.jeremyfeinstein.utils.ConfigUtil;
import com.jeremyfeinstein.utils.YCHSInstance;

import android.content.res.Resources;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MeetingScreenGrid {
    private LinearLayout mContainer;
    private TextView[] tips;
    private TextView[] titles;
    private TextView[] userSNs;
    private View[] lys;
    private View[] bgs;
    private ImageView[] imageViews;
    long mLastTime;
    long mCurTime;

    private static final String TAG = MeetingScreenGrid.class.getSimpleName();

    public MeetingScreenGrid(LinearLayout container, final DoubleClickListener doubleClickListener) {
        setContainer(container);
        tips = new TextView[9];
//        titles = new TextView[9];
        bgs = new RelativeLayout[9];
        lys = new RelativeLayout[9];
        imageViews = new ImageView[9];
        userSNs = new TextView[9];
        for (int i = 0; i < 9; i++) {
            tips[i] = (TextView) mContainer.findViewById(getResId("screen_" + i));
//            titles[i] = (TextView) mContainer.findViewById(getResId("screen_title_" + i));
            userSNs[i] = (TextView) mContainer.findViewById(getResId("user_sn_" + i));
            bgs[i] = mContainer.findViewById(getResId("screen_bg_" + i));
            lys[i] = mContainer.findViewById(getResId("screen_ly_" + i));
            imageViews[i] = (ImageView) mContainer.findViewById(getResId("screen_icon_" + i));
            if (tips[i] != null) {
                tips[i].setText("");
            }
            if (lys[i] != null) {
                final int index = i;
                lys[i].setOnTouchListener(new OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent event) {
                        if (MotionEvent.ACTION_DOWN == event.getAction()) {
                            mLastTime = mCurTime;
                            mCurTime = System.currentTimeMillis();
                            if (mCurTime - mLastTime < 300) {
                                doubleClickListener.onDoubleClick(index + 1);
                                return true;
                       	    } /*else {
								doubleClickListener.onToch();
								return false;
                            }*/
                        }
                        return false;
                    }
                });
            }

//            if (titles[i] != null) {
//                final int index = i;
//                titles[i].setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View com.aspsine.swipetoloadlayout.view) {
//                        doubleClickListener.onToch(titles[index].getText().toString(), userSNs[index].getText().toString());
//                    }
//                });
//            }
        }
    }

    public LinearLayout getContainer() {
        return mContainer;
    }

    public void setContainer(LinearLayout container) {
        this.mContainer = container;
    }

    public void updateAliasName(String userSN, final String aliasName){
        if(userSNs == null){
            return;
        }
//        for (int i = 0; i < userSNs.length; i++) {
//            if(userSNs[i].getText().equals(userSN)){
//                titles[i].setVisibility(View.VISIBLE);
//                titles[i].setText(aliasName);
//                break;
//            }
//        }
    }

    public void restore() {
        for (int i = 0; i < 9; i++) {
            if (i == 8) {
                continue;
            }
            TextView tip = tips[i];
            ImageView imageView = imageViews[i];
            View llView = lys[i];
            if (tip != null) {
                tips[i].setText("");
                tips[i].setVisibility(View.GONE);
//                titles[i].setText("");
//                titles[i].setVisibility(View.GONE);
                userSNs[i].setText("");
                userSNs[i].setVisibility(View.GONE);
                View view = bgs[i];
                llView.setBackgroundResource(R.color.default_person_bg2);
                view.setVisibility(View.VISIBLE);
                if (imageView != null) {
                    imageView.setBackgroundResource(R.drawable.defalt_person);
                }
            }
        }
    }

    public boolean isNotVisible(int i) {
        View view = bgs[i - 1];
        return view.getVisibility() == View.GONE;
    }

    public void setLocalCameraViewGone() {
        TextView tip = tips[8];// (TextView)
        View view = bgs[8];
        if (tip != null) {
            tip.setVisibility(View.GONE);
            if (view != null) {
                view.setVisibility(View.GONE);
            }
        }
    }

    public void updateScreenGrid(ConferenceClient room,
                                 final List<MeetingUser> userList) {
        restore();
        final List<RemoteStream> streams = room.getRemoteStreams();
        final List<MeetingUser> showUserList = new ArrayList<MeetingUser>();
        showUserList.addAll(userList);

//		resetRegion(showUserList, streams,room, showUserList);
        try {
            showRegion(room, streams, showUserList);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(mContainer.getContext(), "网络出现异常,请重新加入互动", Toast.LENGTH_LONG).show();
            restore();
        }
    }

    private void showRegion(ConferenceClient room,
                            final List<RemoteStream> streams,
                            final List<MeetingUser> showUserList) {
        int index = streams.size() - 1;
        /*//20171123 对数组越界 -1 临时处理
        if (index == -1) {
            return;
        }*/
        boolean hasVideoFlag = true;
        for (final MeetingUser user : showUserList) {
            if ("4".equals(user.getRole())) {
                continue;
            }
            System.out.println(user.getName());
            hasVideoFlag = false;
            for (int i = 0; i < streams.size(); i++) {
                System.out.println("rsId size:" + streams.size());
                RemoteStream rs = streams.get(i);
                if ((rs instanceof RemoteMixedStream)
                        || (rs instanceof RemoteScreenStream)) {
                    Log.d(TAG, "showRegion 1: "+"rsId:" + rs.getId()
                            + " userName:" + user.getName());
                } /*else if (!rs.hasPublishedVideo()) {
                    Log.d(TAG, "showRegion 2: "+"rsId:" + rs.getId()
                            + " userName:" + user.getName());
                    index--;
                }*/ else {
                    final RemoteStream rms = rs;
                    if (rms.getId().equals(user.getStreamId())) {
                        room.getRegion(rms, new ActionCallback<String>() {
                            @Override
                            public void onSuccess(final String arg0) {
                                System.out.println("rsId:" + rms.getId()
                                        + " getRegion:" + arg0 + " userName:" + user.getName());
                                int regionIndex = 0;
                                try {
                                    regionIndex = Integer.parseInt(arg0);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                                if (regionIndex > 8 || regionIndex < 1) {
                                    return;
                                }
                                final int rid = regionIndex - 1;
                                mContainer.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        TextView tip = tips[rid];// (TextView)
//                                        TextView title = titles[rid];// (TextView)
                                        TextView userSN = userSNs[rid];// (TextView)
                                        View view = bgs[rid];
                                        View llView = lys[rid];
                                        if (tip != null) {
                                            if ("1".equals(user.getBallFlag())) {
                                                tip.setText("布控球"
                                                        + ":" + user.getName());
                                            } else {
                                                tip.setText(ConfigUtil
                                                        .getRoleName(user.getRole())
                                                        + ":" + user.getName());
//                                                title.setText(user.getAliasName());//每个小视频额头上显示的备注
                                                userSN.setText(user.getUserSN());
                                            }
                                            llView.setBackgroundResource(R.drawable.boder);
                                            tip.setVisibility(View.VISIBLE);
//                                            title.setTextColor(getContainer().getResources().getColor(R.color.whitecolor));
//                                            title.setVisibility(View.VISIBLE);
                                            if (view != null) {
                                                view.setVisibility(View.GONE);
                                            }
                                        }
                                    }

                                });
                            }

                            @Override
                            public void onFailure(WoogeenException arg0) {
                                Log.e("MeetingScreenGrid", arg0.getMessage());
                            }
                        });
                        hasVideoFlag = true;
                        break;
                    }
                }

            }
            if (hasVideoFlag) {
                continue;
            } else {
                TextView tip = tips[index];
//                TextView title = titles[index];
//                if(title != null){
//                    if(title.getText().toString().trim().isEmpty()){
//                        title.setText(user.getAliasName());
//                        title.setVisibility(View.VISIBLE);
//                    }
//                }
                TextView userSN = userSNs[index];
                if(userSN != null){
                    if(userSN.getText().equals("")){
                        userSN.setText(user.getUserSN());
                    }
                }

                if (tip != null) {
                    if (tip.getText().toString().trim().isEmpty()) {
                        tip.setText(user.getName());
                        tip.setVisibility(View.VISIBLE);
                        index++;
                        continue;
                    }
                }
            }
        }
    }


    private void resetRegion(List<MeetingUser> meetingUsers, final List<RemoteStream> remoteStreams, final ConferenceClient room, final List<MeetingUser> showUserList) {
        // TODO Auto-generated method stub
        int userStreamCount = 0;
        int assistantStreamCount = 0;
        RemoteStream hostRemoteStream = null;
        MeetingUser mUser = YCHSConferenceClient.getInstance().getUserByUserCode(YCHSInstance.getInstance().getLoginUser().getUSER_CODE());
        for (RemoteStream stream : remoteStreams) {
            if ((stream instanceof RemoteMixedStream)
                    || (stream instanceof RemoteScreenStream)) {

            } else {
                userStreamCount++;
            }

            for (MeetingUser meetingUser : meetingUsers) {
                if (stream.getId().equals(meetingUser.getStreamId())) {
                    if (YCHSConferenceClient.getInstance().ROLE_ASSISTANT.equals(meetingUser.getRole())) {
                        assistantStreamCount++;
                    }
                    if (YCHSConferenceClient.getInstance().ROLE_PRESENTER.equals(meetingUser.getRole())) {
                        hostRemoteStream = stream;
                    }
                }
            }
        }
        RemoteStream currentUserStream = YCHSConferenceClient.getInstance().getRemoteStreamsById(mUser.getStreamId());
        int region = updateRegion(userStreamCount, assistantStreamCount, hostRemoteStream, mUser);
        room.setRegion(currentUserStream, String.valueOf(region), new ActionCallback<Void>() {

            @Override
            public void onFailure(WoogeenException arg0) {
                try {
                    showRegion(room, remoteStreams, showUserList);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(mContainer.getContext(), "网络出现异常,请重新加入互动", Toast.LENGTH_LONG).show();
                    restore();
                }
            }

            @Override
            public void onSuccess(Void arg0) {
                // TODO Auto-generated method stub
                try {
                    showRegion(room, remoteStreams, showUserList);
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(mContainer.getContext(), "网络出现异常,请重新加入互动", Toast.LENGTH_LONG).show();
                    restore();
                }
            }
        });
    }

    //region 更新 给视频重新 排序
    private int updateRegion(int remoteStreamCount, int assistantCount, RemoteStream hostRemoteStream, MeetingUser mUser) {
        String currentUserRole = mUser.getRole();
        int region = 8;
        if (currentUserRole.equals(YCHSConferenceClient.getInstance().ROLE_PRESENTER)) {
            region = 1;
        } else if (currentUserRole.equals(YCHSConferenceClient.getInstance().ROLE_ASSISTANT)) {
            if (hostRemoteStream != null) {
                region = Math.max(1, Math.min(region, assistantCount + 1));
            } else {
                region = Math.max(1, Math.min(region, assistantCount));
            }
        } else if (currentUserRole.equals(YCHSConferenceClient.getInstance().ROLE_PARTICIPANTS)) {
            region = Math.max(1, Math.min(region, remoteStreamCount));
        }
        return region;
    }

    //		private RemoteStream getHostStream(List<MeetingUser> userList){
//			boolean hasHostStream = false;
//			String hostStreamId = "";
//			for(MeetingUser meetingUser : userList){
//				if(YCHSConferenceClient.getApp().ROLE_PRESENTER.equals(meetingUser.getRole())){
//					hostStreamId = meetingUser.getStreamId();
//					hasHostStream = true;
//					break;
//				}
//			}
//			if(hasHostStream){
//				return YCHSConferenceClient.getApp().getRemoteStreamsById(hostStreamId);
//			}
//			return null;
//		}
    public int getResId(String name) {
        Resources mResources = mContainer.getResources();
        String packageName = mContainer.getContext().getApplicationInfo().packageName;
        return mResources.getIdentifier(name, "id", packageName);
    }

}
